/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twodstar.selfie;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.parse.Parse;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Use a custom Application class to pass state data between Activities.
 */
public class SelfieBattleApplication extends Application 
{

	private String m_FBID;
	private String m_Name = "";
    private List<GraphUser> selectedUsers;
    
    private String[] m_FrdUIDArray;
    private boolean m_IsAlreadyInitFrdUIDs = false;
    
    private static SelfieBattleApplication m_Inst = null;   
    
    private boolean m_IsCurrentlyQueryingFriendList = false;
    private boolean m_ParseInited = false;
    private boolean m_IsFacebookInstalled = false;
    private boolean m_IsCheckFacebook = false;
    
    
           
    public SelfieBattleApplication() 
    {
		// TODO Auto-generated constructor stub
    	m_Inst = this;
    	
    	
	}
    
    public boolean GetIsParseInited()
    {
    	return m_ParseInited;
    }
    
    public static SelfieBattleApplication Instance()
    {
    	return m_Inst;
    }

    public List<GraphUser> getSelectedUsers() 
    {
        return selectedUsers;
    }

    public void setSelectedUsers(List<GraphUser> users) 
    {
        selectedUsers = users;
    }
    
   
    
   
    private void SetAppFriendList(String[] pStrArray)
    {
    	m_FrdUIDArray = new String[pStrArray.length];
    	System.arraycopy(pStrArray, 0, m_FrdUIDArray, 0, pStrArray.length);
    	m_IsAlreadyInitFrdUIDs = true;
    }
    
    public boolean GetIsAlreadyInitFrdUIDs()
    {
    	return m_IsAlreadyInitFrdUIDs;
    }
    
    public String[] GetAppFrdList()
    {
    	return m_FrdUIDArray;
    }

    public void SetFBID(String FBID)
    {
    	m_FBID = FBID;    	
    }
    
    public void SetName(String Name)
    {
    	m_Name = Name;
    }
    
    public String GetFBID()
    {
    	return m_FBID;
    }
    
    public String GetName()
    {
    	return m_Name;
    }
   
    
    @Override
	public void onCreate() 
    {
		super.onCreate();

		Parse.initialize(this, "2n45sPsWC0u2VxEOH8OLKLP9TItQP4q8ip6xvBrg", "8RTFYCE4AHKo9TWrUYiKiJhFnCijINPIHy2Zmw0q");
		
		// Set your Facebook App Id in strings.xml
		ParseFacebookUtils.initialize(getString(R.string.app_id));
		m_ParseInited = true;
	}
    
    public String GetPlayerTitle(ParseUser PU)
	{
    	if(PU != null)
    	{
    		int Level = CalculateLevel(PU.getInt("BattleWin"));
    		
    		if(Level == 0)	// level 0 is just indicating that he hasn't create his first battle yet 
    			Level = 1;
    		
    		Level--; // java start form 0
    		String[] Titles = getResources().getStringArray(R.array.Titles);
    		
    		if(Level < Titles.length)
    		{
    			return Titles[Level];
    		}
    		else if(Level > Titles.length)
    		{
    			return Titles[Titles.length - 1];
    		}
    		
    		if(Titles != null && Titles.length > 0)
    			return Titles[0];
    		
    	}
    	
    	return "";
	}
    
    protected boolean isOnline() 
    {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) 
        {
            return true;
        } 
        else 
        {
            return false;
        }
    }
    
    
    public void LogoutUser()
	{
    	if(m_ParseInited == false)
    		return;
		
		Session session = ParseFacebookUtils.getSession();
		
		if(session != null)
			session.closeAndClearTokenInformation();
		
		if(ParseUser.getCurrentUser() != null)                 									
			ParseUser.logOut();
		
		if( Session.getActiveSession() != null)
			Session.getActiveSession().closeAndClearTokenInformation();
		
		
		Fragment_NewBattle.Instance().Reset();
		Fragment_Battles.Instance().Reset();
		Fragment_Best.Instace().Reset();
		Element_BattleList.Reset();
		
		m_FBID = null;
		m_FrdUIDArray = null;
		m_IsAlreadyInitFrdUIDs = false;
		
	}
    
    
    public int CalculateLevel(int WinBattle)
    {
    	boolean Loop = true;
    	int ReturnLevel = 1;
    	while(Loop)
    	{
    		WinBattle -= ReturnLevel;
    		if(WinBattle >= 0)
    		{
    			ReturnLevel++;
    		}
    		else
    		{
    			Loop = false;
    		}
    	}
    	return ReturnLevel;
    }
    
    public void LoadAPPFriendList()
    {
    	    	
    	Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) 
        {        
        }
        else
        {
        	return;
        }
        
        if(m_IsCurrentlyQueryingFriendList)
        	return;
        
        if(m_IsAlreadyInitFrdUIDs)
        	return;
        
        m_IsCurrentlyQueryingFriendList = true;
        
        String fqlQuery = "SELECT uid FROM user WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1 = me() OR uid2 = me() ) AND is_app_user = 1";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);

        Request request = new Request(session,
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
                public void onCompleted(Response response) 
                {
                	m_IsCurrentlyQueryingFriendList = false;
                	 GraphObject graphObject = response.getGraphObject();
                	
                	 
                	 if (graphObject != null) 
                	 {
                         JSONObject jsonObject = graphObject.getInnerJSONObject();
                         
                         try 
                         {
                             JSONArray array = jsonObject.getJSONArray("data");
                             
                             int Count = array.length();
                             m_FrdUIDArray = new String[Count];
                             for (int i = 0; i < Count; i++) 
                             {
                                 JSONObject object = (JSONObject) array.get(i);
                                 m_FrdUIDArray[i] = object.get("uid").toString();         	 
                             }
                             //SelfieBattleApplication app =  SelfieBattleApplication.Instance();
                             SetAppFriendList(m_FrdUIDArray);
                             
                            
                        } 
                        catch (JSONException e) 
                        {
                        	e.printStackTrace();
                        }	                         
                         
                       
                        
                	 }
               ;
            }
        });        
        
        Request.executeBatchAsync(request);
    }
    
    public boolean GetIsFacebookInstalled()
    {
    	if(m_IsCheckFacebook)
    	{
    		return m_IsFacebookInstalled;
    	}
    	
    	try
    	{
    		if(getPackageManager() != null)
    		{
    			getPackageManager().getApplicationInfo("com.facebook.katana", 0 );
    			m_IsFacebookInstalled = true;
    	    	return true;
    		}
    	} 
    	catch( PackageManager.NameNotFoundException e )
    	{
    		m_IsFacebookInstalled = false;
    	}
    	m_IsCheckFacebook = true;
		return m_IsFacebookInstalled;
    }
    
}
